package com.cmic.rcs.emoji.controller.app;

import com.cmic.rcs.emoji.common.UserContext;

import com.cmic.rcs.emoji.entity.pojo.TDataConfig;
import com.cmic.rcs.emoji.entity.pojo.TEnterpriseMember;
import com.cmic.rcs.emoji.entity.vo.PerformanceEfficiencyVO;
import com.cmic.rcs.emoji.mapper.TEnterpriseMemberMapper;
import com.cmic.rcs.emoji.service.DataConfigService;
import com.cmic.rcs.enhance.message.g5.core.common.ResponseData;
import com.cmic.rcs.enhance.message.g5.core.common.ReturnCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 质效提升视窗控制器
 */
@RestController
@RequestMapping("/api/app/performance-efficiency")
@Slf4j
public class PerformanceEfficiencyController {

    @Autowired
    private DataConfigService dataConfigService;

    @Resource
    private TEnterpriseMemberMapper tEnterpriseMemberMapper;

    /**
     * 获取质效提升视窗数据
     * @return 质效提升视窗数据
     */
    @PostMapping("/getData")
    public ResponseData<PerformanceEfficiencyVO> getPerformanceEfficiencyData() {
        try {
            // 1. 从UserContext获取当前用户手机号
            String phoneNumber = UserContext.getUserDto().getUsername();
            log.info("获取质效提升视窗数据，当前用户手机号：{}", phoneNumber);

            // 2. 根据手机号查询企业成员信息，获取企业编码
            // 使用现有的selectByEncryptedPhone方法，这里直接传入手机号（实际可能需要加密处理）
            TEnterpriseMember member = tEnterpriseMemberMapper.selectByEncryptedPhone(phoneNumber);
            if (member == null) {
                log.error("未找到用户信息，手机号：{}", phoneNumber);
                return new ResponseData<>(ReturnCodeEnum.NULL_EXCEPTION, null);
            }

            String enterpriseCode = member.getEnterpriseCode();
            if (StringUtils.isBlank(enterpriseCode)) {
                log.error("用户企业编码为空，手机号：{}", phoneNumber);
                return new ResponseData<>(ReturnCodeEnum.NULL_EXCEPTION, null);
            }
            log.info("用户所在企业编码：{}", enterpriseCode);

            // 3. 根据企业编码查询质效提升视窗数据配置（先查询EFFICIENCY类型）
            TDataConfig dataConfig = dataConfigService.getDataConfigByEnterpriseCodeAndDataType(enterpriseCode, "EFFICIENCY");
            // 如果没有找到EFFICIENCY类型，尝试查询OPERATION类型
            if (dataConfig == null) {
                dataConfig = dataConfigService.getDataConfigByEnterpriseCodeAndDataType(enterpriseCode, "OPERATION");
            }
            
            // 4. 构建响应数据
            PerformanceEfficiencyVO result = new PerformanceEfficiencyVO();
            
            // TODO 设置默认数据（由于实际数据获取不到）
            result.setRunningDays("1000");
            result.setEnterpriseMembers("4000");
            result.setTotalMessages("98000");
            result.setTotalSecureEmails("3000");
            
            // 从配置获取节省成本和建设周期数据
            if (dataConfig != null) {
                result.setCostSavings(dataConfig.getCostSavings() != null ? String.valueOf(dataConfig.getCostSavings()) : "1000");
                result.setCycleReduction(dataConfig.getCycleReduction() != null ? String.valueOf(dataConfig.getCycleReduction()) : "80");
                result.setCycleDescription(dataConfig.getDataDescription() != null ? dataConfig.getDataDescription() : "平均建设周期由1年降低为2个月");
            } else {
                // 使用默认值
                result.setCostSavings("1000");
                result.setCycleReduction("80");
                result.setCycleDescription("平均建设周期由1年降低为2个月");
            }
            
            log.info("获取质效提升视窗数据成功，企业编码：{}", enterpriseCode);
            return ResponseData.OK(result);
            
        } catch (Exception e) {
            log.error("获取质效提升视窗数据异常：", e);
            // 异常情况下返回默认数据，显示"--"表示获取失败
            PerformanceEfficiencyVO defaultResult = new PerformanceEfficiencyVO();
            defaultResult.setRunningDays("--");
            defaultResult.setEnterpriseMembers("--");
            defaultResult.setTotalMessages("--");
            defaultResult.setTotalSecureEmails("--");
            defaultResult.setCostSavings("--");
            defaultResult.setCycleReduction("--");
            defaultResult.setCycleDescription("数据获取失败");
            
            return new ResponseData<>(ReturnCodeEnum.SYSTEM_ERROR, defaultResult);
        }
    }
}